import { Component } from '@angular/core';
import { NavController, NavParams, ToastController, AlertController } from 'ionic-angular';
import { ValidatePage } from '../validate/validate';
import { ScanPage } from '../scan/scan';
import { Observable } from 'rxjs/Observable';
import { RestService } from '../../app/services/rest.service';
import { TranslateService } from '@ngx-translate/core';

@Component({
  selector: 'page-device',
  templateUrl: 'device.html'
})
export class DevicePage {
  public tabsisvis = false;
  devices = [];
  viewOnly = false;
  public person;
  constructor(private rest: RestService,
    public navParams: NavParams,
    public navCtrl: NavController,
    public translate: TranslateService,
    private toastCtrl: ToastController,
    public alerCtrl: AlertController) {
    this.person = navParams.data;
    if (JSON.parse(localStorage.getItem('devices'))) {
      this.devices = JSON.parse(localStorage.getItem('devices'));
    }
  }

  nav2validate() {
    this.navCtrl.push(ValidatePage, {
      person: this.person,
    });
  }

  nav2scan() {
    this.navCtrl.push(ScanPage, {
      personNamefromDvs: this.person.personName,
      callback: data => {
        console.log(data.info);
        this.devices.push({ id: data.deviceId, name: data.deviceName, netwk: false, disabled: this.person.device1Id!='', bind: false })
        localStorage.setItem('devices', JSON.stringify(this.devices));
      }
    });
  }

  refresh() {
    this.rest.get('/data/person/' + this.person.id).subscribe(data => {
      this.person = data;
    });
  }

  ionViewDidEnter() {
    this.viewOnly = JSON.parse(localStorage.getItem("viewOnly"));
    this.refresh();
    this.devices.forEach(dvc => {
      if (dvc.bind) {
        dvc.netwk = !this.person.deviceAlarmFlag;
      }
    });
  }

  bindunbind(device) {
    //bind
    if (device.bind) {
      this.bind(device);
      this.devices.forEach(dvc => {
        dvc.disabled = true;
      });
      device.disabled = false;
    } else  //unbind
    {
      this.unbind(device);
      this.devices.forEach(dvc => {
        dvc.disabled = false;
      });
    }
    localStorage.setItem('devices', JSON.stringify(this.devices));

  }

  bind(device) {
    const observableBatch = [];

    this.rest.getWithParams('/data/person/search/name', {
      name: localStorage.getItem('personName'),
      institutionId: this.rest.institutionId
    }).subscribe(resp => {
      this.person = resp['_embedded']['persons'][0];
    }, message => {
      console.error('Failed to get all persons in: ' + message);
    });

    this.rest.getWithParams('/data/device/search/deviceId', {
      deviceId: device.id
    }).subscribe(resp => {
      this.person.device1 = resp['_embedded']['devices'][0].id;
      this.person.device1Id = device.id;
      const data = this.person;
      if (data.device1Id) {
        // now device1 is bound, check if original one should be unbinded
        // if (person.device1Id) {
        //   // unbind it firstly
        //   observableBatch.push(this.rest.patch('data/device/' + person.device1, {personId: 0, personName: ''}));
        // }

        observableBatch.push(this.rest.patch('/data/device/' + data.device1, { personId: this.person.id, personName: this.person.personName }));
      }

      observableBatch.push(this.rest.patch('/data/person' + '/' + this.person.id, data));

      Observable.forkJoin(observableBatch).subscribe((resp) => {
        console.log('Bind ' + this.person.personName + ' successfully!');
        this.person.device1Id = device.id;
           this.informPersonChange(this.person.id, device.id,'bind');
      }, message => {
        // this.rest.showHttpError('bindPersonError', message);
      });

    }, message => {
      console.error('Failed to get all persons in: ' + message);
    });

  }

  unbind(device) {
    const observableBatch = [];

    const patchData = {};

    this.rest.getWithParams('/data/device/search/deviceId', {
      deviceId: device.id
    }).subscribe(resp => {
      this.person.device1 = resp['_embedded']['devices'][0].id;
      const data = this.person;
      if (data.device1) {
        observableBatch.push(this.rest.patch('/data/device/' + data.device1, { personId: 0, personName: '' }));
        patchData['device1'] = 0;
        patchData['device1Id'] = '';
      }

      observableBatch.push(this.rest.patch('/data/person' + '/' + this.person.id, patchData));

      Observable.forkJoin(observableBatch).subscribe((resp) => {
        console.log('Unbind ' + this.person.personName + ' successfully!');
        this.informPersonChange(this.person.id, this.person.device1Id,'unbind');
        this.person.device1Id = '';
      }, message => {
        // this.rest.showHttpError('unbindPersonError', message);
      });
    }, message => {
      // this.rest.showHttpError('unbindPersonError', message);
    });
  }

  informPersonChange(personId: string, devId:string,type: string) {
    // type could be checkin, checkout, delete, updateDevice, updateThreshold, updateBasic, updateContact, updateHospital
    this.rest.post('/data/configData', {
      personId: personId,
      devId:devId,
      type: type
    }).subscribe(() => {
    });
  }

  pressEvent(e) {
    if (!this.rest.validated){
      this.nav2validate();
    }else {
      this.deleteConfirm(e.target.innerText);
    }
  }

  deleteConfirm(deviceId) {
    let confirm = this.alerCtrl.create({
      title: this.translate.get('confirmDeleteDevice')['value'],
      message: '',
      buttons: [
        {
          text: this.translate.get('no')['value'],
          handler: () => {
            console.log('Disagree clicked');
          }
        },
        {
          text: this.translate.get('yes')['value'],
          handler: () => {
            this.delete(deviceId);
            console.log('Agree clicked');
          }
        }
      ]
    });
    confirm.present()
  }

  delete(deviceId) {
    this.rest.getWithParams('/data/device/search/deviceId', {
      deviceId: deviceId
    }).subscribe(resp => {
      this.person.device1 = resp['_embedded']['devices'][0].id;
      if (resp['_embedded']['devices'][0].personName == '' || resp['_embedded']['devices'][0].personName == null) {
        this.rest.delete('/data/device/' + this.person.device1).subscribe(result => {
          this.refreshDevices(deviceId);
          // localStorage.setItem('devices', JSON.stringify(this.devices));
        }, message => {
          // this.rest.showHttpError(this.translate.get('error')['value'], message);
        });
      } else {
        this.showToast(this.translate.get('nonEmptyDeviceMessage')['value']);
      }

    }, message => {
      console.error('Failed to get all persons in: ' + message);
    });

  }
  refreshDevices(deviceId) {
    const deviceTmp = [];
    this.devices.forEach(dvc => {
      if (dvc.bind) {
        dvc.netwk = this.person.deviceAlarmFlag;
      }
      if (deviceId != dvc.id) {
        deviceTmp.push(dvc)
      }
    });
    this.devices = deviceTmp;
    localStorage.setItem('devices', JSON.stringify(this.devices));
  }

  showToast(message) {
    const toast = this.toastCtrl.create({
      message: message,
      duration: 3000,
      position: 'middle'
    });

    toast.present(toast);
  }

}
